<template>
  <!-- 任务管理 -->
  <div class="Hcont" v-if="homepage === 4">
    <div class="Hhead" @click="toHcont">
      <div class="hd1">
        <img src="../assets/logo3.png" alt="系统logo" class="hd11">
        <div class="hd12 noselect">
          <div class="hd121">智能配送</div>
          <div class="hd122">Intelligent Distribution</div>
        </div>
      </div>
      <img src="../assets/work.png" alt="工作图标" class="hd2">
      <div class="hd4"></div>
      <div class="hd3">
        <img src="../assets/tou.png" alt="用户头像" class="hd31">
        <el-dropdown>
          <span class="el-dropdown-link noselect xiaoshou" @click.stop>
            Qin<el-icon class="el-icon--right"><ArrowDown /></el-icon>
        </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :icon="Postcard">个人信息</el-dropdown-item>
              <el-dropdown-item :icon="User">AI客服</el-dropdown-item>
              <el-dropdown-item :icon="Setting">设置</el-dropdown-item>
              <el-dropdown-item :icon="Switch">切换账号</el-dropdown-item>
              <el-dropdown-item :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="hb"></div>
    <div class="Hbody">
      <div class="bdl">
        <div class="bdl1">
          <div class="bdl11 noselect xiaoshou" @click="uav" :class="{ 'active-nav': homepage === 2 }">
            <img src="../assets/UAV.png" alt="无人机图标" class="bdl111">
            <div class="bdl112">无人机管理</div>
          </div>
          <div class="bdl12 noselect xiaoshou" @click="mm" :class="{ 'active-nav': homepage === 3 }">
            <img src="../assets/MM.png" alt="商户图标" class="bdl121">
            <div class="bdl122">商户管理</div>
          </div>
          <div class="bdl13 noselect xiaoshou" @click="task" :class="{ 'active-nav': homepage === 4 }">
            <img src="../assets/task.png" alt="任务图标" class="bdl131">
            <div class="bdl132">任务管理</div>
          </div>
          <div class="bdl14 noselect xiaoshou" @click="map" :class="{ 'active-nav': homepage === 5 }">
            <img src="../assets/map.png" alt="地图图标" class="bdl141">
            <div class="bdl142">地图与空域管理</div>
          </div>
          <div class="bdl15 noselect xiaoshou" @click="alarm" :class="{ 'active-nav': homepage === 6 }">
            <img src="../assets/alarm.png" alt="告警图标" class="bdl151">
            <div class="bdl152">告警中心</div>
          </div>
        </div>
      </div>
      <div class="bdr">
        <div class="dashboard-container">
          <!-- 页面标题与数据概览 -->
          <div class="page-header">
            <div class="status-overview">
              <div class="overview-item">
                <span class="overview-label">今日总任务</span>
                <span class="overview-value">{{ totalTodayTasks }}</span>
              </div>
              <div class="overview-item">
                <span class="overview-label">完成率</span>
                <span class="overview-value">{{ completionRate }}%</span>
              </div>
              <div class="overview-item">
                <span class="overview-label">平均配送时间</span>
                <span class="overview-value">{{ avgDeliveryTime }}分钟</span>
              </div>
            </div>
          </div>

          <!-- 筛选栏 -->
          <div class="filter-bar">
            <el-row :gutter="20" class="filter-row">
              <el-col :span="6" :xs="24">
                <el-input 
                  placeholder="搜索订单号/商户名" 
                  v-model="taskSearchKeyword" 
                  clearable
                  class="search-input"
                >
                  <template #prefix>
                    <Search class="search-icon" />
                  </template>
                </el-input>
              </el-col>
              <el-col :span="4" :xs="12">
                <el-select 
                  v-model="taskStatusFilter" 
                  placeholder="筛选状态" 
                  clearable
                  class="filter-select"
                >
                  <el-option label="全部" value=""></el-option>
                  <el-option label="待分配" value="pending"></el-option>
                  <el-option label="配送中" value="delivering"></el-option>
                  <el-option label="即将超时" value="timeout-soon"></el-option>
                  <el-option label="已完成" value="completed"></el-option>
                  <el-option label="已取消" value="cancelled"></el-option>
                </el-select>
              </el-col>
              <el-col :span="4" :xs="12">
                <el-select 
                  v-model="taskPriorityFilter" 
                  placeholder="筛选优先级" 
                  clearable
                  class="filter-select"
                >
                  <el-option label="全部" value=""></el-option>
                  <el-option label="紧急优先" value="urgent"></el-option>
                  <el-option label="常规" value="normal"></el-option>
                  <el-option label="低优先级" value="low"></el-option>
                </el-select>
              </el-col>
              <el-col :span="4" :xs="24">
                <el-date-picker
                  v-model="dateRange"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                  class="date-filter"
                ></el-date-picker>
              </el-col>
              <el-col :span="2" :offset="2" :xs="{ span: 24, offset: 0 }" class="add-btn-col">
                <el-button type="primary" @click="createNewTask" class="add-task-btn">
                  <Plus /> 新建任务
                </el-button>
              </el-col>
            </el-row>
          </div>

          <!-- 任务状态卡片 -->
          <div class="dashboard-cards">
            <el-card class="status-card pending-card" shadow="hover">
              <div class="card-inner">
                <div class="status-icon">
                  <el-icon class="icon-pending"><Clock /></el-icon>
                </div>
                <div class="status-data">
                  <div class="status-label">待分配任务</div>
                  <div class="status-value">{{ pendingCount }}</div>
                  <div class="status-desc">需尽快分配无人机</div>
                </div>
                <div class="status-action">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="batchAssignTasks"
                    :disabled="pendingCount === 0"
                  >
                    批量分配
                  </el-button>
                </div>
              </div>
            </el-card>
            
            <el-card class="status-card delivering-card" shadow="hover">
              <div class="card-inner">
                <div class="status-icon">
                  <el-icon class="icon-delivering"><Van /></el-icon>
                </div>
                <div class="status-data">
                  <div class="status-label">配送中任务</div>
                  <div class="status-value">{{ deliveringCount }}</div>
                  <div class="status-desc">实时监控中</div>
                </div>
                <div class="status-action">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="viewDeliveryMap"
                    :disabled="deliveringCount === 0"
                  >
                    查看地图
                  </el-button>
                </div>
              </div>
            </el-card>
            
            <el-card class="status-card timeout-card" shadow="hover">
              <div class="card-inner">
                <div class="status-icon">
                  <el-icon class="icon-timeout"><Warning /></el-icon>
                </div>
                <div class="status-data">
                  <div class="status-label">即将超时</div>
                  <div class="status-value">{{ timeoutSoonCount }}</div>
                  <div class="status-desc">
                    <span class="timeout-warning">需紧急处理</span>
                  </div>
                </div>
                <div class="status-action">
                  <el-button 
                    type="warning" 
                    size="small" 
                    @click="handleTimeoutTasks"
                    :disabled="timeoutSoonCount === 0"
                  >
                    优先处理
                  </el-button>
                </div>
              </div>
            </el-card>
            
            <el-card class="status-card completed-card" shadow="hover">
              <div class="card-inner">
                <div class="status-icon">
                  <el-icon class="icon-completed"><CheckCircle /></el-icon>
                </div>
                <div class="status-data">
                  <div class="status-label">今日已完成</div>
                  <div class="status-value">{{ completedTodayCount }}</div>
                  <div class="status-desc">
                    <span class="completion-rate">完成率 {{ completionRate }}%</span>
                  </div>
                </div>
                <div class="status-action">
                  <el-button 
                    type="success" 
                    size="small" 
                    @click="exportReport"
                  >
                    导出报表
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 紧急任务提醒 -->
          <div v-if="timeoutSoonCount > 0" class="alert-panel">
            <el-alert
              title="紧急提醒"
              type="warning"
              :closable="false"
              show-icon
            >
              <span>有 {{ timeoutSoonCount }} 个任务即将超时，请优先处理</span>
              <el-button 
                type="text" 
                size="small" 
                @click="handleTimeoutTasks"
                class="alert-action"
              >
                立即处理
              </el-button>
            </el-alert>
          </div>

          <!-- 进行中任务卡片组 -->
          <div class="task-cards-section">
            <div class="section-header">
              <h3 class="section-title">进行中任务</h3>
              <el-button 
                type="text" 
                size="small" 
                @click="viewAllOngoingTasks"
                class="view-all-link"
              >
                查看全部 <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
            
            <!-- 空状态处理 -->
            <div v-if="ongoingTasks.length === 0" class="empty-state">
              <Empty description="当前没有进行中的任务" />
              <el-button 
                type="primary" 
                size="small" 
                @click="createNewTask"
                class="empty-action"
              >
                <Plus /> 创建新任务
              </el-button>
            </div>
            
            <!-- 任务卡片滚动区 -->
            <div v-else class="task-cards-scroll">
              <div 
                class="task-card" 
                v-for="task in ongoingTasks" 
                :key="task.id" 
                @click="viewTaskDetails(task)"
                :class="{ 'urgent-task': task.priority === 'urgent', 'timeout-soon-task': task.status === 'timeout-soon' }"
              >
                <div class="task-header">
                  <span class="task-id">{{ task.orderId }}</span>
                  <el-tag :type="getPriorityTagType(task.priority)" class="priority-tag">
                    {{ getPriorityText(task.priority) }}
                  </el-tag>
                </div>
                
                <div class="task-info">
                  <div class="task-meta">
                    <div class="task-merchant">
                      <el-icon class="meta-icon"><Shop /></el-icon>
                      <span>{{ task.merchantName }}</span>
                    </div>
                    <div class="task-time">
                      <el-icon class="meta-icon"><Clock /></el-icon>
                      <span>创建于 {{ formatTime(task.createTime) }}</span>
                    </div>
                  </div>
                  
                  <div class="delivery-route">
                    <div class="route-item from-location">
                      <el-icon class="location-icon"><Location /></el-icon>
                      <span class="location-text">{{ task.fromLocation }}</span>
                    </div>
                    <div class="route-arrow">
                      <el-icon><ArrowDown /></el-icon>
                    </div>
                    <div class="route-item to-location">
                      <el-icon class="location-icon"><Marker /></el-icon>
                      <span class="location-text">{{ task.toLocation }}</span>
                    </div>
                  </div>
                  
                  <!-- 配送进度条 -->
                  <div class="delivery-progress">
                    <div class="progress-info">
                      <span class="progress-text">配送进度</span>
                    </div>
                    <el-progress 
                      :percentage="task.deliveryProgress" 
                      :stroke-width="4" 
                      :color="getProgressColor(task.deliveryProgress)"
                      class="progress-bar"
                    ></el-progress>
                  </div>
                  
                  <div class="task-stats">
                    <div class="stat-item remaining-time">
                      <el-icon class="stat-icon"><Timer /></el-icon>
                      <span class="stat-text">剩余时间</span>
                      <span class="stat-value" :class="task.remainingTime < 10 ? 'time-warning' : ''">
                        {{ task.remainingTime }}分钟
                      </span>
                    </div>
                    <div class="stat-item drone-info">
                      <el-icon class="stat-icon"><Airplane /></el-icon>
                      <span class="stat-text">无人机</span>
                      <span class="stat-value">{{ task.droneId || '未分配' }}</span>
                    </div>
                  </div>
                </div>
                
                <div class="task-footer">
                  <el-tag :type="getStatusTagType(task.status)" class="status-tag">
                    {{ getStatusText(task.status) }}
                  </el-tag>
                  <el-button type="text" size="small" class="detail-btn">查看详情</el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 任务列表表格 -->
          <div class="task-table-section">
            <el-card class="table-card" shadow="hover">
              <template #header>
                <div class="table-header">
                  <span class="table-title">任务列表</span>
                  <div class="table-actions">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="refreshTaskList"
                      class="refresh-btn"
                    >
                      <Refresh /> 刷新
                    </el-button>
                    <span class="table-count">共 {{ filteredTasks.length }} 条记录</span>
                  </div>
                </div>
              </template>
              
              <div class="table-content">
                <el-table 
                  :data="filteredTasks" 
                  stripe 
                  border
                  style="width: 100%;"
                  @row-click="viewTaskDetails"
                  :row-class-name="tableRowClassName"
                >
                  <el-table-column type="index" label="序号" width="60"></el-table-column>
                  <el-table-column prop="orderId" label="订单编号" width="160"></el-table-column>
                  <el-table-column prop="merchantName" label="商户名称" width="140"></el-table-column>
                  <el-table-column label="配送地址" width="300">
                    <template #default="scope">
                      <div class="address-cell">
                        <div class="address-from">
                          <el-icon class="cell-icon"><Location /></el-icon>
                          <span>{{ scope.row.fromLocation }}</span>
                        </div>
                        <div class="address-to">
                          <el-icon class="cell-icon"><Marker /></el-icon>
                          <span>{{ scope.row.toLocation }}</span>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="priority" label="优先级" width="100">
                    <template #default="scope">
                      <el-tag :type="getPriorityTagType(scope.row.priority)">
                        {{ getPriorityText(scope.row.priority) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                      <el-tag 
                        :type="getStatusTagType(scope.row.status)" 
                        :class="{ 'timeout-tag': scope.row.status === 'timeout-soon' }"
                      >
                        {{ getStatusText(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="剩余时间" width="100">
                    <template #default="scope">
                      <span 
                        :class="scope.row.remainingTime < 10 && scope.row.status !== 'completed' ? 'time-warning' : ''"
                      >
                        {{ scope.row.remainingTime >= 0 && scope.row.status !== 'completed' ? `${scope.row.remainingTime}分钟` : '-' }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                      <el-button 
                        type="text" 
                        size="small" 
                        @click.stop="viewTaskDetails(scope.row)"
                        class="table-btn view-btn"
                      >
                        详情
                      </el-button>
                      <el-button 
                        type="text" 
                        size="small" 
                        @click.stop="handleTaskAction(scope.row)"
                        :disabled="['completed', 'cancelled'].includes(scope.row.status)"
                        class="table-btn action-btn"
                      >
                        {{ getActionText(scope.row.status) }}
                      </el-button>
                      <el-button 
                        type="text" 
                        size="small" 
                        @click.stop="confirmCancelTask(scope.row)"
                        :disabled="['completed', 'cancelled'].includes(scope.row.status)"
                        class="table-btn cancel-btn"
                      >
                        取消
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <!-- 分页 -->
              <div class="table-pagination" v-if="filteredTasks.length > 0">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 50]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="filteredTasks.length"
                ></el-pagination>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 任务详情弹窗 -->
  <el-dialog 
    v-model="taskDetailVisible" 
    title="任务详情" 
    :width="900"
    class="detail-dialog"
    :before-close="handleDialogClose"
  >
    <el-row :gutter="20" class="detail-row">
      <el-col :span="14">
        <!-- 配送地图预览 - 修复图片路径错误 -->
        <div class="delivery-map" v-if="currentTask.status !== 'completed' && currentTask.status !== 'cancelled'">
          <div class="map-placeholder">
            <!-- 使用存在的地图图片或移除图片 -->
            <img src="../assets/map.png" alt="配送地图" class="map-img" v-if="mapImageExists">
            <div v-else class="map-placeholder-placeholder">
              <el-icon class="map-icon"><Map /></el-icon>
              <div class="map-placeholder-text">配送地图预览</div>
            </div>
            <div class="map-marker from-marker">
              <el-icon class="marker-icon"><Location /></el-icon>
              <span class="marker-label">{{ currentTask.fromLocation }}</span>
            </div>
            <div class="map-marker to-marker">
              <el-icon class="marker-icon"><Marker /></el-icon>
              <span class="marker-label">{{ currentTask.toLocation }}</span>
            </div>
            <div class="map-drone">
              <el-icon class="drone-icon"><Airplane /></el-icon>
            </div>
          </div>
        </div>
        
        <!-- 任务信息详情 -->
        <el-descriptions column="1" border class="task-descriptions">
          <el-descriptions-item label="订单编号">{{ currentTask.orderId }}</el-descriptions-item>
          <el-descriptions-item label="商户信息">
            <div class="merchant-info">
              <span class="merchant-name">{{ currentTask.merchantName }}</span>
              <el-button type="text" size="small" @click="gotoMerchantDetail(currentTask)">查看商户</el-button>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="配送信息">
            <div class="delivery-info">
              <div>出发地：{{ currentTask.fromLocation }}</div>
              <div>目的地：{{ currentTask.toLocation }}</div>
              <div>配送距离：{{ currentTask.distance || '未知' }} 公里</div>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="时间线">
            <el-timeline>
              <el-timeline-item 
                timestamp="创建时间" 
                :content="formatFullTime(currentTask.createTime)"
                placement="top"
              ></el-timeline-item>
              <el-timeline-item 
                timestamp="预计送达" 
                :content="formatFullTime(currentTask.estimatedDeliveryTime)"
                placement="top"
              ></el-timeline-item>
              <el-timeline-item 
                timestamp="实际完成" 
                :content="currentTask.completeTime ? formatFullTime(currentTask.completeTime) : '未完成'"
                placement="top"
                v-if="currentTask.status === 'completed'"
              ></el-timeline-item>
            </el-timeline>
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
      
      <el-col :span="10">
        <!-- 任务状态卡片 -->
        <el-card class="status-detail-card" :class="getStatusCardClass(currentTask.status)">
          <div class="status-detail-header">
            <div class="status-text">
              {{ getStatusText(currentTask.status) }}
            </div>
            <el-tag 
              :type="getStatusTagType(currentTask.status)" 
              size="large" 
              class="status-tag-large"
            >
              {{ getStatusText(currentTask.status) }}
            </el-tag>
          </div>
          
          <div class="status-detail-body">
            <div class="detail-item">
              <span class="detail-label">优先级</span>
              <el-tag :type="getPriorityTagType(currentTask.priority)" class="detail-value">
                {{ getPriorityText(currentTask.priority) }}
              </el-tag>
            </div>
            
            <div class="detail-item" v-if="currentTask.status !== 'completed' && currentTask.status !== 'cancelled'">
              <span class="detail-label">剩余时间</span>
              <span class="detail-value" :class="currentTask.remainingTime < 10 ? 'time-warning' : ''">
                {{ currentTask.remainingTime }} 分钟
              </span>
            </div>
            
            <div class="detail-item" v-if="currentTask.droneId">
              <span class="detail-label">无人机</span>
              <span class="detail-value">
                {{ currentTask.droneId }}
                <el-button type="text" size="small" @click="gotoDroneDetail(currentTask)">详情</el-button>
              </span>
            </div>
            
            <div class="detail-item">
              <span class="detail-label">物品信息</span>
              <div class="detail-value">
                <div>类型：{{ currentTask.itemType }}</div>
                <div>重量：{{ currentTask.weight }} kg</div>
              </div>
            </div>
            
            <div class="detail-item">
              <span class="detail-label">电量状态</span>
              <div class="battery-info">
                <el-progress 
                  :percentage="currentTask.droneBattery || 0" 
                  :stroke-width="6" 
                  :color="getBatteryColor(currentTask.droneBattery || 0)"
                  class="battery-progress"
                ></el-progress>
                <span class="battery-percent">{{ currentTask.droneBattery || 0 }}%</span>
              </div>
            </div>
            
            <div class="detail-item">
              <span class="detail-label">备注</span>
              <span class="detail-value remark-value">{{ currentTask.remark || '无' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <template #footer>
      <el-button @click="taskDetailVisible = false">关闭</el-button>
      <el-button 
        type="primary" 
        @click="handleTaskAction(currentTask)"
        :disabled="['completed', 'cancelled'].includes(currentTask.status)"
      >
        {{ getActionText(currentTask.status) }}
      </el-button>
      <el-button 
        type="danger" 
        @click="confirmCancelTask(currentTask)"
        :disabled="['completed', 'cancelled'].includes(currentTask.status)"
      >
        取消任务
      </el-button>
    </template>
  </el-dialog>

  <!-- 批量分配弹窗 -->
  <el-dialog 
    v-model="batchAssignVisible" 
    title="批量分配任务" 
    :width="700"
    class="assign-dialog"
  >
    <el-form 
      :model="assignForm" 
      label-width="100px" 
      ref="assignFormRef"
      class="assign-form"
    >
      <el-form-item label="选择无人机" prop="droneId" required>
        <el-select 
          v-model="assignForm.droneId" 
          placeholder="请选择可用无人机"
          @change="checkDroneCapacity"
        >
          <el-option 
            v-for="drone in availableDrones" 
            :key="drone.id" 
            :label="`${drone.id}（${drone.model}）- 电量${drone.battery}%`" 
            :value="drone.id"
          ></el-option>
        </el-select>
        <div class="drone-capacity-info" v-if="selectedDrone">
          <el-progress 
            :percentage="droneLoadPercentage" 
            :stroke-width="4" 
            class="load-progress"
          ></el-progress>
          <div class="capacity-text">
            <span>负载能力：{{ selectedDrone.capacity }} kg</span>
            <span>剩余续航：{{ selectedDrone.remainingRange }} 公里</span>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="选择任务" required>
        <el-checkbox-group 
          v-model="assignForm.selectedTasks" 
          @change="updateDroneLoad"
        >
          <el-checkbox 
            v-for="task in pendingTasks" 
            :key="task.id" 
            :label="task.id"
            :disabled="isTaskDisabled(task)"
          >
            <div class="task-checkbox-item">
              <div class="task-info-short">
                <div class="task-id-short">{{ task.orderId }}</div>
                <div class="task-location-short">
                  {{ task.fromLocation }} → {{ task.toLocation }}
                </div>
              </div>
              <div class="task-meta-short">
                <span class="task-weight">重量：{{ task.weight }}kg</span>
                <span class="task-priority">
                  <el-tag :type="getPriorityTagType(task.priority)" size="mini">
                    {{ getPriorityText(task.priority) }}
                  </el-tag>
                </span>
              </div>
            </div>
          </el-checkbox>
        </el-checkbox-group>
        <div class="assign-note">
          <el-icon size="14"><InfoFilled /></el-icon>
          <span>一次最多分配3个任务，总重量不超过无人机负载</span>
        </div>
      </el-form-item>
      
      <el-form-item label="预计完成时间">
        <el-time-picker
          v-model="assignForm.estimatedTime"
          placeholder="选择预计完成时间"
          format="HH:mm"
          value-format="HH:mm"
          class="time-picker"
        ></el-time-picker>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="batchAssignVisible = false">取消</el-button>
      <el-button 
        type="primary" 
        @click="confirmBatchAssign"
        :disabled="!assignForm.droneId || assignForm.selectedTasks.length === 0"
      >
        确认分配
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, computed, onMounted, watch } from 'vue'
import {
  ArrowDown, Postcard, User, Setting, Switch, SwitchButton,
  Plus, Search, Warning, Location, Marker, ArrowRight, InfoFilled,
  Clock, CheckCircle, Shop, Timer, Airplane, Van, Refresh, Empty,
  Map // 新增地图图标
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'

// 路由实例初始化
const router = useRouter()

// 页面状态管理
const homepage = ref(4) // 默认为任务管理页面（4）

// 导航方法
const toHcont = () => { 
  homepage.value = 1
  router.push('/HomeViews') 
}
const uav = () => { 
  homepage.value = 2
  router.push('/navViews') 
}
const mm = () => { 
  homepage.value = 3
  router.push('/mmViews') 
}
const task = () => { 
  homepage.value = 4
  router.push('/taskViews') 
}
const map = () => { 
  homepage.value = 5
  router.push('/mapViews') 
}
const alarm = () => { 
  homepage.value = 6
  router.push('/alarmViews') 
}

// 任务管理相关变量 - 修复ref访问错误
const taskSearchKeyword = ref('')
const taskStatusFilter = ref('')
const taskPriorityFilter = ref('')
const dateRange = ref('') // 默认今天
const taskDetailVisible = ref(false)
const batchAssignVisible = ref(false)
const currentTask = ref({})
const currentPage = ref(1)
const pageSize = ref(10)
const mapImageExists = ref(false) // 标记地图图片是否存在

// 任务分配表单 - 修复ref访问错误
const assignForm = ref({
  droneId: '',
  selectedTasks: [],
  estimatedTime: ''
})

// 无人机数据
const drones = ref([
  { 
    id: 'UAV-001', 
    model: '顺丰方舟-300', 
    status: 'online', 
    battery: 85,
    capacity: 5, // 负载能力(kg)
    remainingRange: 42, // 剩余续航(公里)
    currentLoad: 0 // 当前负载
  },
  { 
    id: 'UAV-002', 
    model: '京东飞侠-200', 
    status: 'idle', 
    battery: 92,
    capacity: 3,
    remainingRange: 55,
    currentLoad: 0
  },
  { 
    id: 'UAV-003', 
    model: '美团闪电-100', 
    status: 'online', 
    battery: 42,
    capacity: 4,
    remainingRange: 28,
    currentLoad: 1.2
  }
])

// 任务数据
const tasks = ref([
  {
    id: '1',
    orderId: '#DR-20240714-0852',
    merchantName: '城市咖啡店',
    fromLocation: '万达仓',
    toLocation: '科技园A座',
    createTime: '2025-07-14 08:32',
    estimatedDeliveryTime: '2025-07-14 09:15',
    remainingTime: 23,
    status: 'delivering',
    priority: 'urgent',
    droneId: 'UAV-001',
    droneBattery: 87,
    droneLocation: '科技园区上空',
    distance: 3.2,
    deliveryProgress: 65,
    itemType: '饮品',
    weight: 1.2,
    remark: '需要保持水平放置'
  },
  {
    id: '2',
    orderId: '#DR-20240714-0915',
    merchantName: '鲜果汁吧',
    fromLocation: '步行街店',
    toLocation: '创意园B区',
    createTime: '2025-07-14 09:05',
    estimatedDeliveryTime: '2025-07-14 09:40',
    remainingTime: 38,
    status: 'delivering',
    priority: 'normal',
    droneId: 'UAV-002',
    droneBattery: 65,
    droneLocation: '创意园附近',
    distance: 2.5,
    deliveryProgress: 40,
    itemType: '鲜榨果汁',
    weight: 0.8,
    remark: '冷藏保存'
  },
  {
    id: '3',
    orderId: '#DR-20240714-0930',
    merchantName: '健康药房',
    fromLocation: '医疗园区店',
    toLocation: '居民小区C区',
    createTime: '2025-07-14 09:20',
    estimatedDeliveryTime: '2025-07-14 09:50',
    remainingTime: 8,
    status: 'timeout-soon',
    priority: 'urgent',
    droneId: 'UAV-003',
    droneBattery: 42,
    droneLocation: '居民小区附近',
    distance: 2.8,
    deliveryProgress: 85,
    itemType: '药品',
    weight: 0.5,
    remark: '需冷藏，紧急配送'
  },
  {
    id: '4',
    orderId: '#DR-20240714-0845',
    merchantName: '便民超市',
    fromLocation: '中心店',
    toLocation: '阳光花园',
    createTime: '2025-07-14 08:25',
    estimatedDeliveryTime: '2025-07-14 09:00',
    remainingTime: 0,
    status: 'completed',
    completeTime: '2025-07-14 08:58',
    priority: 'normal',
    droneId: 'UAV-001',
    droneBattery: 72,
    distance: 4.5,
    deliveryProgress: 100,
    itemType: '日用品',
    weight: 2.5,
    remark: ''
  },
  {
    id: '5',
    orderId: '#DR-20240714-0942',
    merchantName: '数码配件店',
    fromLocation: '电子城店',
    toLocation: '科技园C座',
    createTime: '2025-07-14 09:30',
    estimatedDeliveryTime: '2025-07-14 10:10',
    remainingTime: 25,
    status: 'pending',
    priority: 'low',
    droneId: '',
    droneBattery: 0,
    distance: 2.1,
    deliveryProgress: 0,
    itemType: '手机配件',
    weight: 0.3,
    remark: ''
  },
  {
    id: '6',
    orderId: '#DR-20240714-0955',
    merchantName: '鲜花礼品店',
    fromLocation: '步行街店',
    toLocation: '幸福小区',
    createTime: '2025-07-14 09:45',
    estimatedDeliveryTime: '2025-07-14 10:20',
    remainingTime: 22,
    status: 'pending',
    priority: 'normal',
    droneId: '',
    droneBattery: 0,
    distance: 3.8,
    deliveryProgress: 0,
    itemType: '鲜花',
    weight: 1.0,
    remark: '轻拿轻放，避免挤压'
  },
  {
    id: '7',
    orderId: '#DR-20240714-0750',
    merchantName: '城市咖啡店',
    fromLocation: '万达仓',
    toLocation: '科技园区D座',
    createTime: '2025-07-14 07:40',
    estimatedDeliveryTime: '2025-07-14 08:20',
    remainingTime: 0,
    status: 'cancelled',
    priority: 'normal',
    droneId: '',
    droneBattery: 0,
    distance: 2.7,
    deliveryProgress: 0,
    itemType: '咖啡',
    weight: 0.6,
    remark: '客户取消订单'
  }
])

// 任务筛选与排序
const filteredTasks = computed(() => {
  return tasks.value.filter(task => {
    const matchesKeyword = 
      task.orderId.toLowerCase().includes(taskSearchKeyword.value.toLowerCase()) ||
      task.merchantName.toLowerCase().includes(taskSearchKeyword.value.toLowerCase())
    const matchesStatus = !taskStatusFilter.value || task.status === taskStatusFilter.value
    const matchesPriority = !taskPriorityFilter.value || task.priority === taskPriorityFilter.value
    const matchesDate = !dateRange.value || task.createTime.startsWith(dateRange.value)
    return matchesKeyword && matchesStatus && matchesPriority && matchesDate
  }).sort((a, b) => {
    const priorityMap = { urgent: 1, normal: 2, low: 3 }
    const statusMap = { 'timeout-soon': 1, delivering: 2, pending: 3, completed: 4, cancelled: 5 }
    
    if (statusMap[a.status] !== statusMap[b.status]) {
      return statusMap[a.status] - statusMap[b.status]
    }
    if (priorityMap[a.priority] !== priorityMap[b.priority]) {
      return priorityMap[a.priority] - priorityMap[b.priority]
    }
    return new Date(b.createTime) - new Date(a.createTime)
  })
})

// 进行中的任务（用于卡片组）
const ongoingTasks = computed(() => {
  return tasks.value.filter(task => ['delivering', 'timeout-soon', 'pending'].includes(task.status))
    .sort((a, b) => {
      const statusMap = { 'timeout-soon': 1, delivering: 2, pending: 3 }
      if (statusMap[a.status] !== statusMap[b.status]) {
        return statusMap[a.status] - statusMap[b.status]
      }
      return a.remainingTime - b.remainingTime
    }).slice(0, 5); // 只显示前5个
})

// 任务状态统计
const pendingCount = computed(() => tasks.value.filter(task => task.status === 'pending').length)
const deliveringCount = computed(() => tasks.value.filter(task => task.status === 'delivering').length)
const timeoutSoonCount = computed(() => tasks.value.filter(task => task.status === 'timeout-soon').length)
const completedTodayCount = computed(() => {
  const today = new Date().toISOString().split('T')[0]
  return tasks.value.filter(task => 
    task.status === 'completed' && 
    task.createTime.startsWith(today)
  ).length
})

// 今日任务统计
const totalTodayTasks = computed(() => {
  const today = new Date().toISOString().split('T')[0]
  return tasks.value.filter(task => task.createTime.startsWith(today)).length
})

const completionRate = computed(() => {
  const todayTasks = tasks.value.filter(task => task.createTime.startsWith(new Date().toISOString().split('T')[0]))
  if (todayTasks.length === 0) return 0
  const completed = todayTasks.filter(task => task.status === 'completed').length
  return Math.round((completed / todayTasks.length) * 100)
})

const avgDeliveryTime = computed(() => {
  const completedTasks = tasks.value.filter(task => task.status === 'completed' && task.completeTime)
  if (completedTasks.length === 0) return 0
  const totalMinutes = completedTasks.reduce((total, task) => {
    const create = new Date(task.createTime)
    const complete = new Date(task.completeTime)
    return total + Math.round((complete - create) / (1000 * 60))
  }, 0)
  return Math.round(totalMinutes / completedTasks.length)
})

// 待分配任务与可用无人机
const pendingTasks = computed(() => tasks.value.filter(task => task.status === 'pending'))
const availableDrones = computed(() => drones.value.filter(drone => drone.status === 'online' || drone.status === 'idle'))

// 分配任务相关计算属性
const selectedDrone = computed(() => {
  return drones.value.find(drone => drone.id === assignForm.value.droneId) || null
})

const selectedTasks = computed(() => {
  return tasks.value.filter(task => assignForm.value.selectedTasks.includes(task.id))
})

const totalSelectedWeight = computed(() => {
  return selectedTasks.value.reduce((total, task) => total + task.weight, 0)
})

const droneLoadPercentage = computed(() => {
  if (!selectedDrone.value) return 0
  return Math.min(Math.round((totalSelectedWeight.value / selectedDrone.value.capacity) * 100), 100)
})

// 辅助方法：状态与优先级文本转换
const getStatusText = (status) => {
  const statusMap = {
    pending: '待分配',
    delivering: '配送中',
    'timeout-soon': '即将超时',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getPriorityText = (priority) => {
  const priorityMap = {
    urgent: '紧急优先',
    normal: '常规',
    low: '低优先级'
  }
  return priorityMap[priority] || priority
}

const getActionText = (status) => {
  const actionMap = {
    pending: '分配',
    delivering: '追踪',
    'timeout-soon': '处理',
    completed: '查看',
    cancelled: '查看'
  }
  return actionMap[status] || '操作'
}

// 样式相关方法
const getStatusTagType = (status) => {
  const typeMap = {
    pending: 'info',
    delivering: 'primary',
    'timeout-soon': 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

const getPriorityTagType = (priority) => {
  const typeMap = {
    urgent: 'danger',
    normal: 'primary',
    low: 'info'
  }
  return typeMap[priority] || 'info'
}

const getProgressColor = (progress) => {
  if (progress < 30) return '#409EFF'
  if (progress < 70) return '#67C23A'
  return '#E6A23C'
}

const getBatteryColor = (level) => {
  if (level < 20) return '#F56C6C'
  if (level < 50) return '#E6A23C'
  return '#67C23A'
}

const getStatusCardClass = (status) => {
  const classMap = {
    pending: 'status-pending',
    delivering: 'status-delivering',
    'timeout-soon': 'status-timeout',
    completed: 'status-completed',
    cancelled: 'status-cancelled'
  }
  return classMap[status] || ''
}

// 工具方法：时间格式化
const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

const formatFullTime = (timeStr) => {
  const date = new Date(timeStr)
  return date.toLocaleString()
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.status === 'timeout-soon') return 'timeout-row'
  if (row.priority === 'urgent') return 'urgent-row'
  return ''
}

// 任务操作方法 - 修复ref访问错误
const viewTaskDetails = (task) => {
  currentTask.value = { ...task }
  taskDetailVisible.value = true
}

const batchAssignTasks = () => {
  assignForm.value.droneId = ''
  assignForm.value.selectedTasks = []
  assignForm.value.estimatedTime = ''
  batchAssignVisible.value = true
}

const updateDroneLoad = () => {
  // 当选择任务变化时更新无人机负载状态
  if (selectedDrone.value) {
    selectedDrone.value.currentLoad = totalSelectedWeight.value
  }
}

const isTaskDisabled = (task) => {
  if (!selectedDrone.value) return false
  // 最多选择3个任务
  if (assignForm.value.selectedTasks.length >= 3 && !assignForm.value.selectedTasks.includes(task.id)) {
    return true
  }
  // 检查重量是否超过无人机负载
  const tempTotal = totalSelectedWeight.value + (assignForm.value.selectedTasks.includes(task.id) ? 0 : task.weight)
  return tempTotal > selectedDrone.value.capacity
}

const confirmBatchAssign = () => {
  // 修复ref访问错误
  if (!assignForm.value.droneId || assignForm.value.selectedTasks.length === 0) {
    ElMessage.warning('请选择无人机和任务')
    return
  }

  // 更新任务状态
  const currentTasks = tasks.value;
  tasks.value = currentTasks.map(task => {
    if (assignForm.value.selectedTasks.includes(task.id)) {
      return {
        ...task,
        status: 'delivering',
        droneId: assignForm.value.droneId,
        estimatedDeliveryTime: `${dateRange.value || new Date().toISOString().split('T')[0]} ${assignForm.value.estimatedTime || '10:00'}`,
        deliveryProgress: 10 // 初始进度
      }
    }
    return task
  })

  ElNotification.success({
    title: '分配成功',
    message: `已为 ${assignForm.value.selectedTasks.length} 个任务分配无人机 ${assignForm.value.droneId}`,
    duration: 3000
  })
  
  batchAssignVisible.value = false
}

const confirmCancelTask = (task) => {
  ElMessageBox.confirm(
    `确定要取消任务 ${task.orderId} 吗？`,
    '确认取消',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const index = tasks.value.findIndex(t => t.id === task.id)
    if (index !== -1) {
      tasks.value[index].status = 'cancelled'
      tasks.value[index].remark = `${tasks.value[index].remark || ''} (用户取消于 ${new Date().toLocaleString()})`
      ElMessage.success(`已取消任务 ${task.orderId}`)
    }
  }).catch(() => {
    // 取消操作
  })
}

const createNewTask = () => {
  ElMessageBox.prompt('请输入任务名称', '新建任务', {
    confirmButtonText: '创建',
    cancelButtonText: '取消',
    inputPlaceholder: '例如：紧急药品配送'
  }).then(({ value }) => {
    // 模拟创建任务
    const newTask = {
      id: `${tasks.value.length + 1}`,
      orderId: `#DR-${new Date().toISOString().slice(0,10).replace(/-/g,'')}-${Math.floor(Math.random()*1000)}`,
      merchantName: value,
      fromLocation: '默认仓库',
      toLocation: '未知地址',
      createTime: new Date().toLocaleString(),
      estimatedDeliveryTime: new Date(Date.now() + 3600000).toLocaleString(),
      remainingTime: 60,
      status: 'pending',
      priority: 'normal',
      droneId: '',
      droneBattery: 0,
      distance: Math.random() * 5 + 1,
      deliveryProgress: 0,
      itemType: '普通物品',
      weight: 1.0,
      remark: '手动创建的任务'
    }
    tasks.value.unshift(newTask)
    ElNotification.success({
      title: '创建成功',
      message: `新任务 ${newTask.orderId} 已创建`,
      duration: 2000
    })
  }).catch(() => {
    // 取消创建
  })
}

const handleTaskAction = (task) => {
  if (task.status === 'pending') {
    // 分配任务
    currentTask.value = { ...task }
    batchAssignTasks()
  } else if (['delivering', 'timeout-soon'].includes(task.status)) {
    // 追踪任务
    ElNotification.info({
      title: '追踪中',
      message: `正在追踪任务 ${task.orderId} 的实时位置`,
      duration: 2000
    })
  }
}

// 页面交互方法
const viewAllOngoingTasks = () => {
  taskStatusFilter.value = ''
  taskPriorityFilter.value = ''
  // 滚动到表格区域
  setTimeout(() => {
    document.querySelector('.task-table-section')?.scrollIntoView({ behavior: 'smooth' })
  }, 100)
}

const refreshTaskList = () => {
  // 模拟刷新动画
  const refreshBtn = document.querySelector('.refresh-btn')
  refreshBtn?.classList.add('refreshing')
  setTimeout(() => {
    refreshBtn?.classList.remove('refreshing')
    ElMessage.success('任务列表已刷新')
  }, 800)
}

const viewDeliveryMap = () => {
  ElMessage.info('正在打开实时配送地图...')
  // 实际项目中可跳转至地图页面
  // router.push('/delivery-map')
}

const exportReport = () => {
  ElMessage.success('今日任务报表导出成功')
}

const handleTimeoutTasks = () => {
  // 筛选出即将超时的任务并显示
  taskStatusFilter.value = 'timeout-soon'
  // 滚动到表格区域
  setTimeout(() => {
    document.querySelector('.task-table-section')?.scrollIntoView({ behavior: 'smooth' })
  }, 100)
}

const gotoMerchantDetail = (task) => {
  // 跳转到商户详情
  mm() // 切换到商户管理页面
  ElMessage.info(`正在查看商户：${task.merchantName}`)
}

const gotoDroneDetail = (task) => {
  // 跳转到无人机详情
  uav() // 切换到无人机管理页面
  ElMessage.info(`正在查看无人机：${task.droneId}`)
}

const handleDialogClose = () => {
  taskDetailVisible.value = false
  batchAssignVisible.value = false
}

// 分页方法
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 初始化与定时任务
onMounted(() => {
  // 设置默认日期为今天
  dateRange.value = new Date().toISOString().split('T')[0]
  
  // 检查地图图片是否存在
  // 实际项目中可通过HTTP请求检查图片是否存在
  mapImageExists.value = false; // 假设图片不存在
  
  // 定时更新任务状态
  const timer = setInterval(() => {
    tasks.value = tasks.value.map(task => {
      if (['delivering', 'timeout-soon'].includes(task.status)) {
        // 更新剩余时间
        const newRemaining = task.remainingTime - 1
        
        // 更新配送进度
        let newProgress = task.deliveryProgress
        if (task.status !== 'timeout-soon') {
          newProgress = Math.min(task.deliveryProgress + 1, 100)
        }
        
        // 检查是否超时或完成
        if (newRemaining <= 0 && task.status !== 'completed') {
          if (task.deliveryProgress >= 100) {
            // 标记为完成
            return {
              ...task,
              status: 'completed',
              completeTime: new Date().toLocaleString(),
              remainingTime: 0,
              deliveryProgress: 100
            }
          } else {
            // 标记为超时
            return {
              ...task,
              status: 'timeout-soon',
              remainingTime: newRemaining,
              deliveryProgress: newProgress
            }
          }
        }
        
        return {
          ...task,
          remainingTime: newRemaining,
          deliveryProgress: newProgress
        }
      }
      return task
    })
  }, 60000) // 每分钟更新一次
  
  // 清理定时器
  return () => clearInterval(timer)
})

// 监听日期变化 - 修复ref访问错误
watch(dateRange, () => {
  currentPage.value = 1 // 日期变化时重置分页
})
</script>

<style scoped>
/* 基础样式 */
.Hcont{
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  width: 97vw;
  height: 98vh;
  overflow: hidden;
  background-color: rgb(239, 239, 238);
}
.Hhead{
  height: 100px;
  width: 100%;
  background-color: rgb(86, 119, 231);
  display: flex;
  align-items: center;
}
.hd1{
  display: flex;
  margin-left: 60px;
}
.hd11{
  width: 60px;
  border-radius: 100%;
  margin-right: 20px;
}
.hd12{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.hd121{
  font-size: 24px;
  font-weight: 500;
  letter-spacing: 3px;
  color: white;
}
.hd122{
  font-size: 12px;
  color: white;
}
.hd2{
  margin-left: 100px;
  width: 70px;
  margin-top: 30px;
}
.hd3{
  margin-right: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.hd31{
  width: 50px;
  border-radius: 100%;
  margin-right: 10px;
}
.el-dropdown-link{
  color: white;
  outline: none;
  display: flex;
  align-items: center;
}
.hd4{
  flex: 1;
}
.hb{
  width: 100%;
  height: 1px;
  background-color: #e5e7eb;
}
.Hbody{
  display: flex;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}
.bdl{
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 280px;
  background-color: rgb(30, 58, 138);
  transition: width 0.3s ease;
}
.bdl1{
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: center;
  margin-top: 50px;
}
.bdl11,.bdl12,.bdl13,.bdl14,.bdl15{
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
}
.bdl11:hover,.bdl12:hover,.bdl13:hover,.bdl14:hover,.bdl15:hover{
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px); 
  background-color: rgb(156, 188, 249);
  border-radius: 10px;
}
.bdl11:active,.bdl12:active,.bdl13:active,.bdl14:active,.bdl15:active{
  transform: scale(0.97);
  box-shadow: 0 4px 6px -1px rgba(93, 102, 122, 0.1);
}
.bdl111,.bdl121,.bdl131,.bdl141,.bdl151{
  width: 20px;
  padding-right: 10px;
}
.bdl112,.bdl122,.bdl132,.bdl142,.bdl152{
  font-size: 24px;
  font-weight: 400;
  color: white;
}
.active-nav {
  background-color: rgb(156, 188, 249);
  border-radius: 10px;
}
.bdr {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}
.dashboard-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

/* 页面标题与概览 */
.page-header {
  margin-bottom: 25px;
}



.status-overview {
  display: flex;
  gap: 20px;
  margin-top: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.overview-item {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.overview-label {
  font-size: 14px;
  color: #606266;
}

.overview-value {
  font-size: 24px;
  font-weight: 500;
  color: #1f2329;
  margin-top: 5px;
}

/* 筛选栏样式 */
.filter-bar {
  margin-top: 10px;
  margin-bottom: 20px;
}

.filter-row {
  width: 100%;
  background-color: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-input {
  width: 100%;
  transition: all 0.3s;
}

.search-input:focus-within {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.search-icon {
  color: #c0c4cc;
}

.filter-select, .date-filter {
  width: 100%;
}

.add-btn-col {
  display: flex;
  justify-content: flex-end;
}

.add-task-btn {
  width: 100%;
  transition: all 0.2s;
}

.add-task-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 任务状态卡片 */
.dashboard-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin: 20px 0 30px;
}

.status-card {
  height: 160px;
  border-radius: 8px;
  transition: all 0.3s;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.status-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-inner {
  display: flex;
  height: 100%;
  padding: 15px;
}

.status-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
}

.icon-pending {
  font-size: 24px;
  color: #409EFF;
}

.icon-delivering {
  font-size: 24px;
  color: #67C23A;
}

.icon-timeout {
  font-size: 24px;
  color: #F56C6C;
}

.icon-completed {
  font-size: 24px;
  color: #13CE66;
}

.status-data {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.status-label {
  font-size: 16px;
  color: #606266;
  margin-bottom: 5px;
}

.status-value {
  font-size: 36px;
  font-weight: 500;
  margin-bottom: 3px;
}

.status-desc {
  font-size: 14px;
  color: #909399;
}

.status-action {
  display: flex;
  align-items: center;
  justify-content: center;
}

.pending-card .status-icon {
  background-color: rgba(64, 158, 255, 0.1);
}

.delivering-card .status-icon {
  background-color: rgba(103, 194, 58, 0.1);
}

.timeout-card .status-icon {
  background-color: rgba(245, 108, 108, 0.1);
}

.timeout-warning {
  color: #F56C6C;
  font-weight: 500;
}

.completion-rate {
  color: #67C23A;
  font-weight: 500;
}

/* 紧急提醒面板 */
.alert-panel {
  margin: 15px 0;
}

.alert-action {
  margin-left: 15px;
  padding: 0;
  height: auto;
}

/* 任务卡片区域 */
.task-cards-section {
  margin: 5px 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 18px;
  color: #303133;
  font-weight: 500;
}

.view-all-link {
  color: #409EFF;
  display: flex;
  align-items: center;
}

.task-cards-scroll {
  display: flex;
  overflow-x: auto;
  padding: 10px 0;
  gap: 15px;
  scrollbar-width: thin;
}

.task-cards-scroll::-webkit-scrollbar {
  height: 6px;
}

.task-cards-scroll::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}

.task-card {
  min-width: 300px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 18px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s;
}

.task-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
}

.urgent-task {
  border-left: 4px solid #F56C6C;
}

.timeout-soon-task {
  animation: pulse 2s infinite;
  border-left: 4px solid #E6A23C;
}

@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(230, 162, 60, 0.2); }
  70% { box-shadow: 0 0 0 8px rgba(230, 162, 60, 0); }
  100% { box-shadow: 0 0 0 0 rgba(230, 162, 60, 0); }
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #e4e7ed;
}

.task-id {
  font-weight: 500;
}

.priority-tag {
  height: 24px;
  line-height: 24px;
}

.task-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.task-meta {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.meta-icon {
  color: #909399;
  margin-right: 5px;
}

.delivery-route {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10px 0;
}

.route-item {
  display: flex;
  align-items: center;
  width: 100%;
}

.from-location {
  color: #303133;
}

.to-location {
  color: #606266;
}

.location-icon {
  margin-right: 8px;
}

.location-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 280px;
}

.route-arrow {
  margin: 8px 0;
  color: #909399;
}

.delivery-progress {
  margin: 10px 0;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  margin-bottom: 5px;
}

.progress-text {
  color: #606266;
}



.task-stats {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-icon {
  margin-right: 5px;
  color: #909399;
}

.stat-text {
  color: #606266;
  font-size: 14px;
}

.stat-value {
  margin-left: 5px;
}

.time-warning {
  color: #F56C6C;
  font-weight: 500;
}

.task-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 12px;
  border-top: 1px dashed #e4e7ed;
}

.status-tag {
  height: 24px;
  line-height: 24px;
}

.detail-btn {
  color: #409EFF;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.empty-action {
  margin-top: 20px;
}

/* 任务表格样式 */
.table-card {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 18px;
  font-weight: 500;
}

.table-actions {
  display: flex;
  align-items: center;
}

.refresh-btn {
  display: flex;
  align-items: center;
  margin-right: 15px;
  transition: all 0.3s;
}

.refreshing {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.table-count {
  color: #606266;
}

.table-content {
  margin: 15px 0;
}

.table-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.timeout-row {
  background-color: rgba(245, 108, 108, 0.05) !important;
}

.urgent-row {
  background-color: rgba(64, 158, 255, 0.05) !important;
}

.address-cell {
  display: flex;
  flex-direction: column;
}

.address-from, .address-to {
  display: flex;
  align-items: center;
  margin: 2px 0;
}

.cell-icon {
  margin-right: 5px;
  color: #909399;
}

.table-btn {
  padding: 0 5px !important;
}

.view-btn {
  color: #409EFF;
}

.action-btn {
  color: #67C23A;
}

.cancel-btn {
  color: #F56C6C;
}

/* 任务详情弹窗 */
.detail-dialog {
  border-radius: 10px;
}

.detail-row {
  margin-bottom: 20px;
}

.delivery-map {
  height: 200px;
  border-radius: 8px;
  background-color: #f5f7fa;
  margin-bottom: 20px;
  position: relative;
}

.map-placeholder {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.map-marker {
  position: absolute;
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 5px 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-size: 14px;
}

.from-marker {
  top: 20%;
  left: 15%;
}

.to-marker {
  bottom: 20%;
  right: 15%;
}

.marker-icon {
  margin-right: 5px;
}

.marker-label {
  white-space: nowrap;
}

.map-drone {
  position: absolute;
  top: 45%;
  left: 45%;
  width: 30px;
  height: 30px;
  background-color: #409EFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  animation: pulse-drone 2s infinite;
}

.drone-icon {
  font-size: 18px;
}

@keyframes pulse-drone {
  0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4); }
  70% { transform: scale(1.05); box-shadow: 0 0 0 10px rgba(64, 158, 255, 0); }
  100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(64, 158, 255, 0); }
}

.task-descriptions {
  margin-top: 15px;
}

.merchant-info {
  display: flex;
  align-items: center;
}

.merchant-name {
  margin-right: 15px;
}

.delivery-info > div {
  margin: 5px 0;
}

.status-detail-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.status-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.status-text {
  font-size: 24px;
  font-weight: 500;
}

.status-tag-large {
  height: 32px;
  line-height: 32px;
}

.status-detail-body {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.detail-item {
  display: flex;
}

.detail-label {
  width: 80px;
  color: #606266;
  text-align: right;
  margin-right: 15px;
}

.detail-value {
  flex: 1;
  color: #303133;
}

.battery-info {
  display: flex;
  align-items: center;
}

.battery-progress {
  flex: 1;
  margin-right: 10px;
}

.battery-percent {
  min-width: 30px;
  text-align: right;
}

.remark-value {
  max-height: 60px;
  overflow-y: auto;
  display: block;
}

.status-pending {
  border-top: 4px solid #409EFF;
}

.status-delivering {
  border-top: 4px solid #67C23A;
}

.status-timeout {
  border-top: 4px solid #F56C6C;
}

.status-completed {
  border-top: 4px solid #13CE66;
}

.status-cancelled {
  border-top: 4px solid #909399;
}

/* 批量分配弹窗 */
.assign-dialog {
  border-radius: 10px;
}

.assign-form {
  margin: 15px 0;
}

.drone-capacity-info {
  margin-top: 10px;
}

.load-progress {
  margin-bottom: 5px;
}

.capacity-text {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #606266;
}

.task-checkbox-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 10px;
  transition: all 0.2s;
}

.task-checkbox-item:hover {
  border-color: #409EFF;
  background-color: rgba(64, 158, 255, 0.05);
}

.task-info-short {
  display: flex;
  flex-direction: column;
}

.task-id-short {
  font-weight: 500;
  margin-bottom: 5px;
}

.task-location-short {
  font-size: 14px;
  color: #606266;
  max-width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.task-meta-short {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.task-weight {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.assign-note {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #909399;
  margin-top: 10px;
}

.time-picker {
  width: 100%;
}

/* 全局样式 */
.noselect {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.xiaoshou {
  cursor: pointer;
}

/* 响应式样式 */
@media (max-width: 1400px) {
  .dashboard-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .bdl {
    width: 220px;
  }
  
  .bdl112, .bdl122, .bdl132, .bdl142, .bdl152 {
    font-size: 20px;
  }
  
  .hd1 {
    margin-left: 30px;
  }
  
  .hd2 {
    margin-left: 50px;
  }
  
  .hd3 {
    margin-right: 30px;
  }
}

@media (max-width: 1024px) {
  .filter-row {
    flex-wrap: wrap;
  }
  
  .el-col {
    margin-bottom: 15px;
  }
  
  .add-btn-col {
    justify-content: flex-start;
  }
  
  .task-cards-section {
    margin: 20px 0;
  }
  
  .task-card {
    min-width: 300px;
  }
  
  .location-text {
    max-width: 240px;
  }
  
  .detail-dialog {
    width: 90% !important;
  }
  
  .assign-dialog {
    width: 90% !important;
  }
}

@media (max-width: 768px) {
  .dashboard-cards {
    grid-template-columns: 1fr;
  }
  
  .status-overview {
    flex-wrap: wrap;
  }
  
  .overview-item {
    flex-basis: 50%;
    margin-bottom: 15px;
  }
  
  .bdl {
    width: 60px;
  }
  
  .bdl112, .bdl122, .bdl132, .bdl142, .bdl152 {
    display: none;
  }
  
  .bdl111, .bdl121, .bdl131, .bdl141, .bdl151 {
    padding-right: 0;
  }
  
  .hd12 {
    display: none;
  }
  
  .hd2 {
    display: none;
  }
  
  .hd1 {
    margin-left: 20px;
  }
  
  .hd3 {
    margin-right: 20px;
  }
}
</style>